<script setup>
import {ref} from 'vue'
import {uploadCloudFile} from "src/utils/database";
import {Dialog, Notify, Loading} from "quasar";

const files = ref(null)
const viewCustomer = ref(false)
const props = defineProps(['modelValue', 'title'])
const emitSelf = defineEmits(['update:modelValue'])
const viewType = ref('upload')
const options = [
  {
    label: '上传图片',
    value: 'upload',
  },
  {
    label: 'URL',
    value: 'url',
  },
]
// console.log(props.title)
// console.log(props.modelValue)

async function onUploadFile() {
  // console.log(files.value)
  // console.log(props.modelValue)
  Loading.show({
    message: '数据上传中...'
  })

  const res = await uploadCloudFile(files.value)
  viewCustomer.value = false
  Loading.hide()

  if (!res) {
    Notify.create({
      message: '上传失败'
    })
  } else {
    Notify.create({
      message: '上传成功'
    })
    // console.log('success', res)
    // console.log('download_url', res.download_url)
    emitSelf('update:modelValue', res.download_url)
    viewCustomer.value = false
  }
}

function selectFile() {
  viewCustomer.value = true
  // upimg.click()
}

</script>

<template>
  <div>
    <q-option-group
        v-model="viewType"
        :options="options"
        color="primary"
        inline
    />
    <q-tab-panels v-model="viewType" animated class="shadow-2 rounded-borders">
      <q-tab-panel name="upload">

        <q-list>
          <q-item v-ripple>

            <q-item-section style="max-width: 100px">
              <q-img :src="modelValue" alt="" style="max-width: 120px" @click="selectFile">
                <div class="absolute-bottom text-body1 text-center" v-if="title!==undefined">
                  {{ title }}
                </div>
              </q-img>
            </q-item-section>

            <q-item-section>
              <q-file ref="upimg" v-model="files" outlined>
                <template v-slot:after>
                  <q-btn round dense flat label="上传" @click="onUploadFile"/>
                </template>
              </q-file>
            </q-item-section>
          </q-item>
        </q-list>

      </q-tab-panel>

      <q-tab-panel name="url">
        <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" class="full-width"/>
      </q-tab-panel>

    </q-tab-panels>

  </div>
</template>

<style scoped>

</style>
